package cn.dancepeak.course.controller;

import cn.dancepeak.exception.BusinessException;
import cn.dancepeak.course.domain.Course;
import cn.dancepeak.course.query.CourseQuery;
import cn.dancepeak.course.service.ICourseServiceImpl;
import cn.dancepeak.utils.ExcelUtil;
import cn.dancepeak.utils.R;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/course")
@Slf4j
public class CourseController {
    //接收yml里的配置文件：E:\\file\\
    @Value("${file.file-path}")
    private String path;
    @Autowired
    private ICourseServiceImpl courseService;

    //接收前端上传的文件
    @PostMapping("/upload")
    //MultipartFile file  接收前端处传来的文件
    public R upload(MultipartFile file) throws IOException {
        //得到上传文件的全名称加后缀（源文件名）
        String filename = file.getOriginalFilename();
        //为了防止新文件和源文件名字冲突重命名
        //1.取后缀
        String suffix = filename.split("\\.")[1];
        //2.重命名  通过现在的时间戳
        String filePath = path + System.currentTimeMillis() + "." + suffix;
        //准备输出流，把文件写到服务器
        File file1 = new File(filePath);
        //如果文件不存在则创建
        if(!file1.exists()){
            file1.mkdirs();//级联创建
        }
        //上传文件
        file.transferTo(file1);
        return R.ok("上传成功！");
    }

    //下载超链接
    @GetMapping("/download")
    public void download(String fileName, HttpServletResponse response) throws IOException {
        //1.设置响应头，告诉浏览器文件下载的名字，附件表示做下载或上传操作
        // attachment:告诉浏览器，以弹框的方式打开我的附件
        response.setHeader("Content-Disposition","attachment; filename=" + fileName);
        String filePath = path + fileName; // D:filel231413241324132412.txt
        FileInputStream inputStream = new FileInputStream(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        //输入流读取到内容之后，需要写入到输出流中即可完成下载
        IOUtils.copy(inputStream,outputStream);
    }

    //导出
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        //1.查询出课表所有信息
        List<Course> Course = courseService.getCourse();
        //2.使用easyPoi工具类导出
        ExcelUtil.exportExcel(Course,"课表信息","",Course.class,"课表信息",response);
    }

    //1.增
    @PostMapping("/add")
    public R<Void> add(@RequestBody Course course){
        try {
            courseService.add(course);
            return R.ok("新增成功");
        } catch (BusinessException e) {
            log.info("新增用户异常：{}",e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.info("新增系统异常：{}",e.getMessage());
            return R.fail(e.getMessage());
        }
    }
    //2.根据ID改
    @PostMapping("/update")
    public R<Void> update(@RequestBody Course course){
        try {
            courseService.update(course);
            return R.ok("修改成功");
        } catch (BusinessException e) {
            log.info("修改用户异常：{}",e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.info("修改系统异常：{}",e.getMessage());
            return R.fail(e.getMessage());
        }
    }
    //3.根据ID删
    @DeleteMapping("/{id}")
    public R<Void> delete(@PathVariable("id") Long id){
        try {
            courseService.delete(id);
            return R.ok("删除成功");
        } catch (BusinessException e) {
            log.info("删除用户异常：{}",e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.info("删除系统异常：{}",e.getMessage());
            return R.fail(e.getMessage());
        }
    }
    //4.批量删
    @PostMapping("/deleteByList")
    public R<Void> deleteByList(@RequestBody List<Long> ids){
        try {
            courseService.deleteByList(ids);
            return R.ok("删除成功");
        } catch (BusinessException e) {
            log.info("删除用户异常：{}",e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.info("删除系统异常：{}",e.getMessage());
            return R.fail(e.getMessage());
        }
    }
    //5.根据ID查
    @GetMapping("/{id}")
    public R<Course> getById(@PathVariable("id") Long id){
        try {
            Course course = courseService.getById(id);
            return R.ok(course);
        } catch (BusinessException e) {
            log.info("查询用户异常：{}",e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.info("查询系统异常：{}",e.getMessage());
            return R.fail(e.getMessage());
        }
    }
    //6.分页查询
    @PostMapping("/page")
    public R<PageInfo<Course>> page(@RequestBody CourseQuery courseQuery){
        try {
            PageInfo<Course> page = courseService.page(courseQuery);
            return R.ok(page);
        } catch (BusinessException e) {
            log.info("查询用户异常：{}",e.getMessage());
            return R.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.info("查询系统异常：{}",e.getMessage());
            return R.fail(e.getMessage());
        }
    }
}
